package org.squabble.web.admin;

import java.util.Map;

import javax.annotation.security.RolesAllowed;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.squabble.SquabbleConstants;
import org.squabble.domain.SystemProperty;
import org.squabble.service.SystemService;

@Controller
@RequestMapping("/admin/system/settings")
public class SystemSettingsController extends AbstractSystemController {

	@Autowired
	SystemService systemService;

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(ModelMap modelMap) {
		SystemSettingsCommand sc = new SystemSettingsCommand();
		Map<String, SystemProperty> props = systemService
				.getSystemPropertyMap();
		sc
				.setSystemCacheTime((Long) getPropertyValue(props,
						"systemCacheTime"));
		sc.setSystemEnabled((Boolean) getPropertyValue(props, "systemEnabled"));
		sc.setSystemMaintenanceMessage(props.get("systemMaintenanceMessage")
				.getValue().toString());
		sc.setSystemSiteURL(props.get("systemSiteURL").getValue().toString());
		sc.setSystemSiteName(props.get("systemSiteName").getValue().toString());
		sc.setUserRegistrationAllow((Boolean) getPropertyValue(props,
				"userRegistrationAllow"));
		sc.setUserRegistrationApproval((Boolean) getPropertyValue(props,
				"userRegistrationApproval"));
		modelMap.addAttribute("systemSettingsCommand", sc);
		return "admin.system.settings";
	}

	@RolesAllowed("ROLE_ADMIN")
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(ModelMap map,
			@ModelAttribute("systemSettingsCommand") SystemSettingsCommand sc) {
		systemService.updateSystemProperties(sc);
		map.addAttribute(SquabbleConstants.POST_PROCESS_MESSAGE,
				"system.processed");
		return "redirect:/admin/system/settings";
	}

}
